package net.facelib.jni;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import net.facelib.akcore.ProductInitStatus;

import static com.google.common.base.Preconditions.checkNotNull;
import static net.facelib.jni.BridgeLog.BRIDEG_LOGGER;

/**
 * 创建{@link BaseJniBridge}实例的工厂类,用于commons-pool2资源池的实例管理
 * @author guyadong
 *
 * @param <T> 资源类型
 */
public class BaseInstanceFactory<T extends BaseJniBridge> implements PooledObjectFactory<T> {
	private final Class<T> type;
	public BaseInstanceFactory(Class<T> type) {
        this.type = checkNotNull(type,"type is null");
	}
	@Override
	public PooledObject<T> makeObject() throws Exception {
		T instance = type.newInstance();
		instance.init();
		BRIDEG_LOGGER.log("{} {}",type.getName(),instance.hashCode());
		return new DefaultPooledObject<T>( instance );
	}
	@Override
	public void destroyObject(PooledObject<T> p) throws Exception {
		BRIDEG_LOGGER.log("{} {}",type.getName(),p.getObject().hashCode());
		p.getObject().destroy();
	}

	@Override
	public boolean validateObject(PooledObject<T> p) {
		// 初始化成功的实例为有效实例
		return ProductInitStatus.PRODUCT_INIT_OK.equals(p.getObject().getStatus().asProductInitStatus());
	}

	@Override
	public void activateObject(PooledObject<T> p) throws Exception {
		// DO NOTHING
	}

	@Override
	public void passivateObject(PooledObject<T> p) throws Exception {
		// DO NOTHING
	}
	public Class<T> getType() {
		return type;
	}

}